﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using SPSocialTagCounters.Helpers;

namespace SPSocialTagCounters.Layouts.SPSocialTagCounters
{
    public partial class settings : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Web.CurrentUser == null || !Web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
            {
                SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
            }

            BtnApply.Click += new EventHandler(BtnApply_Click);
            btnReset.Click += new EventHandler(btnReset_Click);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // Set property bag values to the textboxes
            tbHtml.Text = SPContext.Current.Site.RootWeb.GetPropertyValue(SPPropertyBagHelper.HTMLKey);
            tbCss.Text  = SPContext.Current.Site.RootWeb.GetPropertyValue(SPPropertyBagHelper.StyleKey);
            tbJS.Text   = SPContext.Current.Site.RootWeb.GetPropertyValue(SPPropertyBagHelper.JSKey);
        }

        private void BtnApply_Click(object sender, EventArgs e)
        {
            SPContext.Current.Site.RootWeb.AddPropertyAndUpdate(SPPropertyBagHelper.HTMLKey, tbHtml.Text);
            SPContext.Current.Site.RootWeb.AddPropertyAndUpdate(SPPropertyBagHelper.StyleKey, tbCss.Text);
            SPContext.Current.Site.RootWeb.AddPropertyAndUpdate(SPPropertyBagHelper.JSKey, tbJS.Text);
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            SPContext.Current.Site.RootWeb.AddPropertyAndUpdate(SPPropertyBagHelper.HTMLKey, LayoutHelper.HTML);
            SPContext.Current.Site.RootWeb.AddPropertyAndUpdate(SPPropertyBagHelper.StyleKey, LayoutHelper.CSS);
            SPContext.Current.Site.RootWeb.AddPropertyAndUpdate(SPPropertyBagHelper.JSKey, LayoutHelper.JS);

            tbHtml.Text = LayoutHelper.HTML;
            tbCss.Text = LayoutHelper.CSS;
            tbJS.Text = LayoutHelper.JS;
        }
    }
}
